"""
数据库配置管理
"""
import os
import json
from typing import Optional

class DatabaseSettings:
    """数据库配置"""
    
    def __init__(self):
        # 尝试从JSON配置文件加载配置
        self._load_from_json()
        # 环境变量优先级更高，覆盖JSON配置
        self._load_from_env()
    
    def _load_from_json(self):
        """从JSON配置文件加载配置"""
        try:
            config_path = os.path.join(os.path.dirname(__file__), '..', '..', 'config', 'app.json')
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
            
            db_config = config.get('database', {})
            connection = db_config.get('connection', {})
            pool = db_config.get('pool', {})
            
            # 数据库连接配置
            self.DB_HOST = connection.get('host', 'localhost')
            self.DB_PORT = connection.get('port', 3306)
            self.DB_USER = connection.get('user', 'monitor_user')
            self.DB_PASSWORD = connection.get('password', 'monitor_password')
            self.DB_NAME = connection.get('name', 'monitor_system')
            self.DB_CHARSET = connection.get('charset', 'utf8mb4')
            
            # 数据库连接池配置
            self.DB_POOL_SIZE = pool.get('pool_size', 10)
            self.DB_MAX_OVERFLOW = pool.get('max_overflow', 20)
            self.DB_POOL_TIMEOUT = pool.get('pool_timeout', 30)
            self.DB_POOL_RECYCLE = pool.get('pool_recycle', 3600)
            
            # URL模板
            self.DB_URL_TEMPLATE = db_config.get('url_template', "mysql+pymysql://{user}:{password}@{host}:{port}/{name}?charset={charset}")
        except Exception as e:
            print(f"警告: 无法加载JSON配置文件，使用默认配置: {e}")
            self._set_defaults()
    
    def _load_from_env(self):
        """从环境变量加载配置（优先级更高）"""
        # 数据库连接配置
        self.DB_HOST = os.getenv("DB_HOST", self.DB_HOST)
        self.DB_PORT = int(os.getenv("DB_PORT", str(self.DB_PORT)))
        self.DB_USER = os.getenv("DB_USER", self.DB_USER)
        self.DB_PASSWORD = os.getenv("DB_PASSWORD", self.DB_PASSWORD)
        self.DB_NAME = os.getenv("DB_NAME", self.DB_NAME)
        self.DB_CHARSET = os.getenv("DB_CHARSET", self.DB_CHARSET)
        
        # 数据库连接池配置
        self.DB_POOL_SIZE = int(os.getenv("DB_POOL_SIZE", str(self.DB_POOL_SIZE)))
        self.DB_MAX_OVERFLOW = int(os.getenv("DB_MAX_OVERFLOW", str(self.DB_MAX_OVERFLOW)))
        self.DB_POOL_TIMEOUT = int(os.getenv("DB_POOL_TIMEOUT", str(self.DB_POOL_TIMEOUT)))
        self.DB_POOL_RECYCLE = int(os.getenv("DB_POOL_RECYCLE", str(self.DB_POOL_RECYCLE)))
    
    def _set_defaults(self):
        """设置默认配置"""
        self.DB_HOST = 'localhost'
        self.DB_PORT = 3306
        self.DB_USER = 'monitor_user'
        self.DB_PASSWORD = 'monitor_password'
        self.DB_NAME = 'monitor_system'
        self.DB_CHARSET = 'utf8mb4'
        self.DB_POOL_SIZE = 10
        self.DB_MAX_OVERFLOW = 20
        self.DB_POOL_TIMEOUT = 30
        self.DB_POOL_RECYCLE = 3600
        self.DB_URL_TEMPLATE = "mysql+pymysql://{user}:{password}@{host}:{port}/{name}?charset={charset}"
    
    # 构建数据库URL
    @property
    def DATABASE_URL(self) -> str:
        """构建数据库连接URL"""
        return self.DB_URL_TEMPLATE.format(
            user=self.DB_USER,
            password=self.DB_PASSWORD,
            host=self.DB_HOST,
            port=self.DB_PORT,
            name=self.DB_NAME,
            charset=self.DB_CHARSET
        )

# 创建全局数据库配置实例
db_settings = DatabaseSettings()